package com.example.eventbusdemo;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.eventbusdemo.events.FirstEvent;
import com.example.eventbusdemo.events.FourthEvent;
import com.example.eventbusdemo.events.MessageEvent;
import com.example.eventbusdemo.events.SecondEvent;
import com.example.eventbusdemo.events.ThirdEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * @author wdl
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView tvShowEvent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btnToSecondActivity = findViewById(R.id.btn_second_activity);
        btnToSecondActivity.setOnClickListener(this);
        tvShowEvent = findViewById(R.id.tv_event);
        //1.注册
        EventBus.getDefault().register(this);
    }

    /**
     * 2.订阅者
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        String msg = event.getMessage();
        int messageType = event.getMessageType();
        Toast.makeText(MainActivity.this, messageType + ":" + msg, Toast.LENGTH_SHORT).show();
        if (messageType == 0) {
            tvShowEvent.setText(msg);
        }
    }


    /**
     * 多种订阅类型
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMain(FirstEvent event) {

        String msg = event.getMessgae();
        Log.d("EventTAG", "onEventMain: " + event.getMessgae());
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onEventPosting(SecondEvent event) {

        String msg = event.getMessage();
        Log.d("EventTAG", "onEventPosting: " + msg);
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onEventBackground(ThirdEvent event) {

        String msg = event.getMessage();
        Log.d("EventTAG", "onEventBackgroud: " + msg);
    }

    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void onEventAsync(FourthEvent event) {

        String msg = event.getMessage();
        Log.d("EventTAG", "onEventAsync: " + msg);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_second_activity) {
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            startActivity(intent);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //3.注销
        EventBus.getDefault().unregister(this);
    }
}
